import {
  CallHandler,
  ExecutionContext,
  Injectable,
  NestInterceptor,
  LoggerService,
  Inject,
} from '@nestjs/common'
import { map, Observable } from 'rxjs'

@Injectable()
export class ResponseInterceptor implements NestInterceptor {
  constructor(
    @Inject('WINSTON_LOGGER') private readonly logger: LoggerService,
  ) {}
  intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
    return next.handle().pipe(
      map((data) => {
        // 如果data为null或undefined，返回数据不存在的消息
        if (data === null || data === undefined) {
          this.logger.error('请求失败', ResponseInterceptor.name)
          return {
            data: null,
            message: '数据不存在',
            code: 404,
          }
        }
        // 正常返回数据
        return {
          data,
          message: 'success',
          code: 200,
        }
      }),
    )
  }
}
